package mbp.tests;


import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

import mbp.base.FeatureType;
import mbp.base.ResourceType;
import mbp.core.Resource;
import mbp.core.ResourceTypeBuilder;
import mbp.core.ResourceUtility;
import mbp.core.ResourceValidation;
import mbp.exceptions.InvalidEnumTypeException;
import mbp.exceptions.InvalidFeatureNameException;
import mbp.exceptions.InvalidFeatureTypeException;
import mbp.exceptions.InvalidFeatureValueException;
import mbp.exceptions.InvalidResourceTypeException;
import mbp.exceptions.ParseExpressionErrorException;
import mbp.gui.base.EachRowEditor;


/**
 * Graficzny interfejs uzytkownika agenta ResourceAgent. 
 * Agent przeznaczony do tesowania klas reprezentujacych ZASOB.
 * @author Wojciech Wilanski
 *
 */
public class ResourceAgentGui extends JFrame implements ActionListener
{
	private ResourceAgent myAgent;
	private JTextField txtResourceName, txtFeatureName, txtOwner, txtValidDate, txtSend, txtUtilityStr, 
	                   txtValuesStr, txtUUID;
	private JComboBox cmbTypesXml, cmbTypes, cmbResources, cmbUtilityFc, cmbAccFc;
	private JButton btnLoadXml, btnFeature, btnCreate, btnSet, btnDateNow, btnPrint, btnSend, 
	                btnUtilSet, btnUtilCalc, btnCreateUtil, btnAccSet, btnAccCheck, btnCreateAcc;
	private JList listFeatures;
	private JPopupMenu popupMenu;
	private JMenuItem jmi1;
	private DefaultListModel listModel;
	private ResourceType resourceType;
	private Resource resource;
	private HashMap<String, Resource> resourcesStore;
	HashMap<String, FeatureType> features;
	ResourceTypeBuilder typeBuilder;
	boolean adding;
	
	private JTable dt;
    private DefaultTableModel model;
    
    private JTable dtUtilities;
    private DefaultTableModel modelUtilities;
    private DefaultTableModel modelAcc;
    
    private ResourceUtility utilityFunction;
    private HashMap<String, ResourceUtility> utilityFunctionStore;
    
    private ResourceValidation valuesRange;
    private HashMap<String, ResourceValidation> valuesRangeStore;
    private JLabel lblEnumItemaValues;
	
	public ResourceAgentGui(ResourceAgent a)
	{
		super(a.getLocalName());
		myAgent = a;
		features = new HashMap<String, FeatureType>();
		resourcesStore = new HashMap<String, Resource>();
		utilityFunctionStore = new HashMap<String, ResourceUtility>();
		valuesRangeStore = new HashMap<String, ResourceValidation>();
		adding = false;
		
		this.setBounds(150,10,900,480);
		getContentPane().setLayout(null);
		Container content = getContentPane();
		
		JPanel panel0 = new JPanel();
		panel0.setLocation(5, 5);
		panel0.setSize(290, 82);
		panel0.setLayout(null);
		panel0.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Resource Type Fom XML"));
		
		JPanel panel1 = new JPanel();
		panel1.setLocation(5, 88);
		panel1.setSize(290, 217);
		panel1.setLayout(null);
		panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Resource Type (Not working yet)"));
		
		JPanel panel2 = new JPanel();
		panel2.setLocation(300, 5);
		panel2.setSize(290, 300);
		panel2.setLayout(null);
		panel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Resource"));
		
		JPanel panel3 = new JPanel();
		panel3.setLocation(5, 306);
		panel3.setSize(585, 136);
		panel3.setLayout(null);
		panel3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Functions"));
		
		JPanel panel4 = new JPanel();
		panel4.setLocation(595, 5);
		panel4.setSize(290, 300);
		panel4.setLayout(null);
		panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Resource utility"));
		
		JPanel panel5 = new JPanel();
		panel5.setLocation(595, 306);
		panel5.setSize(290, 136);
		panel5.setLayout(null);
		panel5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Resource acceptability"));
		
		//Elementy panel 0
		cmbTypesXml = new JComboBox();
		cmbTypesXml.setLocation(10, 20);
		cmbTypesXml.setSize(80, 20);
		this.LoadFromXml("");
		
		txtValuesStr = new JTextField();
		txtValuesStr.setLocation(10, 67);
		txtValuesStr.setSize(270, 20);
		
		panel0.add(cmbTypesXml);
		
		//Elementy panel 1 ----------------------------------------
		JLabel lblResource = new JLabel("Type Name");
        lblResource.setLocation(10, 20);
        lblResource.setSize(100, 20);
		
		txtResourceName = new JTextField();
		txtResourceName.setLocation(10, 40);
		txtResourceName.setSize(100, 20);
		
		
		JLabel lblFeature = new JLabel("Feature Name");
        lblFeature.setLocation(10, 60);
        lblFeature.setSize(100, 20);
        
        txtFeatureName = new JTextField();
        txtFeatureName.setLocation(10, 80);
        txtFeatureName.setSize(100, 20);
        
        JLabel lblFeatureT = new JLabel("Feature Type");
        lblFeatureT.setLocation(115, 60);
        lblFeatureT.setSize(100, 20);
        
        cmbTypes = new JComboBox();
        cmbTypes.setLocation(115, 80);
        cmbTypes.setSize(80, 20);
        cmbTypes.addItem(mbp.base.FeatureType.INT);
        cmbTypes.addItem(mbp.base.FeatureType.FLOAT);
        cmbTypes.addItem(mbp.base.FeatureType.ENUM);
        
        btnFeature = new JButton("Add");
        btnFeature.setFont(new Font("Arial", Font.PLAIN, 11));
        btnFeature.setName("FEATURE");
        btnFeature.setLocation(200, 80);
        btnFeature.setSize(79, 20);
        
        listModel = new DefaultListModel();
        listFeatures = new JList(listModel);
        //listFeatures.getInputMap().
        listFeatures.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(listFeatures);
        scroll.setLocation(10, 110);
        scroll.setSize(270, 96);
        
        popupMenu = new JPopupMenu();
        jmi1 = new JMenuItem("Delete");
        jmi1.setName("DELETE");
        popupMenu.add(jmi1);
		
		
		panel1.add(lblResource);
		panel1.add(txtResourceName);
		//panel1.add(cmbTypesXml);
		//panel1.add(btnLoadXml);
		panel1.add(lblFeature);
		panel1.add(txtFeatureName);
		panel1.add(lblFeatureT);
		panel1.add(cmbTypes);
		panel1.add(btnFeature);
		panel1.add(scroll);
		
		//Elementy panel 2 (Resource)--------------------------------------
		cmbResources = new JComboBox();
		cmbResources.setLocation(10, 22);
		cmbResources.setSize(120, 20);
		
		txtUUID = new JTextField();
		txtUUID.setEditable(false);
		txtUUID.setLocation(10, 53);
		txtUUID.setSize(270, 20);
		
		model = new DefaultTableModel();
		model.addColumn("Feature Name");
		model.addColumn("Feature Type");
		model.addColumn("Feature Value");
		dt = new JTable(model);
		dt.setFillsViewportHeight(true);
		JScrollPane scrollPane = new JScrollPane(dt);
		scrollPane.setLocation(10, 74);
		scrollPane.setSize(270, 100);
		
		btnSet = new JButton("Set");
        btnSet.setFont(new Font("Arial", Font.PLAIN, 11));
        btnSet.setName("SET");
        btnSet.setLocation(10, 270);
        btnSet.setSize(79, 20);
        
        JLabel lblOwner = new JLabel("Owner");
        lblOwner.setLocation(10, 180);
        lblOwner.setSize(100, 14);
        
        txtOwner = new JTextField(a.getLocalName());
        txtOwner.setLocation(10, 196);
        txtOwner.setSize(160, 20);
        
        JLabel lblValdDate = new JLabel("Valid Date (UTC)");
        lblValdDate.setLocation(10, 224);
        lblValdDate.setSize(150, 14);
        
        txtValidDate = new JTextField("yyyy-MM-ddTHH:mm:ss.SSS");
        txtValidDate.setLocation(10, 240);
        txtValidDate.setSize(160, 20);
        
        btnDateNow = new JButton("+ 5min");
        btnDateNow.setFont(new Font("Arial", Font.PLAIN, 11));
        btnDateNow.setName("NOW");
        btnDateNow.setLocation(180, 240);
        btnDateNow.setSize(80, 20);
		
        panel2.add(cmbResources);
        panel2.add(txtUUID);
		panel2.add(scrollPane);
		panel2.add(btnSet);
		panel2.add(lblOwner);
		panel2.add(txtOwner);
		panel2.add(lblValdDate);
		panel2.add(txtValidDate);
		panel2.add(btnDateNow);
		
		
		//Elementy panel 3
		btnPrint = new JButton("Print");
		btnPrint.setFont(new Font("Arial", Font.PLAIN, 11));
		btnPrint.setName("PRINT");
		btnPrint.setLocation(10, 30);
		btnPrint.setSize(80, 20);
		
		btnSend = new JButton("Send to");
		btnSend.setFont(new Font("Arial", Font.PLAIN, 11));
		btnSend.setName("SEND");
		btnSend.setLocation(95, 30);
		btnSend.setSize(80, 20);
		
		txtSend = new JTextField("receiver");
		txtSend.setLocation(180, 30);
		txtSend.setSize(160, 20);
		
		panel3.add(btnPrint);
		panel3.add(btnSend);
		panel3.add(txtSend);
		//end panel 3
		
		//Elementy panel 4
		cmbUtilityFc = new JComboBox();
		cmbUtilityFc.setLocation(10, 20);
		cmbUtilityFc.setSize(100, 20);
		
		JLabel lblUtility = new JLabel("Utility expression");
		lblUtility.setLocation(10, 56);
		lblUtility.setSize(150, 14);
		
		txtUtilityStr = new JTextField();
		txtUtilityStr.setLocation(10, 71);
		txtUtilityStr.setSize(270, 20);
		
		modelUtilities = new DefaultTableModel();
		modelUtilities.addColumn("Feature Name");
		modelUtilities.addColumn("Enum Value");
		modelUtilities.addColumn("Int Value");
		dtUtilities = new JTable(modelUtilities);
		dtUtilities.setFillsViewportHeight(true);
		JScrollPane spUtilities = new JScrollPane(dtUtilities);
		spUtilities.setLocation(10, 121);
		spUtilities.setSize(270, 123);
		
		btnUtilSet = new JButton("Set");
		btnUtilSet.setFont(new Font("Arial", Font.PLAIN, 11));
		btnUtilSet.setName("UT_SET");
		btnUtilSet.setLocation(10, 269);
		btnUtilSet.setSize(80, 20);
		
		btnUtilCalc = new JButton("Calculate");
		btnUtilCalc.setFont(new Font("Arial", Font.PLAIN, 11));
		btnUtilCalc.setName("UT_CALC");
		btnUtilCalc.setLocation(100, 269);
		btnUtilCalc.setSize(80, 20);
		
		panel4.add(cmbUtilityFc);
		panel4.add(lblUtility);
		panel4.add(txtUtilityStr);
		panel4.add(spUtilities);
		panel4.add(btnUtilSet);
		panel4.add(btnUtilCalc);
		//end panel 4
		
		//Elementy panel 5
		cmbAccFc = new JComboBox();
		cmbAccFc.setLocation(10, 22);
		cmbAccFc.setSize(100, 20);
		
		modelAcc = new DefaultTableModel();
		modelAcc.addColumn("Feature Name");
		modelAcc.addColumn("Condition");
		
		btnAccSet = new JButton("Set");
		btnAccSet.setFont(new Font("Arial", Font.PLAIN, 11));
		btnAccSet.setName("ACC_SET");
		btnAccSet.setLocation(10, 105);
		btnAccSet.setSize(80, 20);
		
		btnAccCheck = new JButton("Check");
		btnAccCheck.setFont(new Font("Arial", Font.PLAIN, 11));
		btnAccCheck.setName("ACC_CHECK");
		btnAccCheck.setLocation(100, 105);
		btnAccCheck.setSize(80, 20);
		
		panel5.add(cmbAccFc);
		panel5.add(txtValuesStr);
		panel5.add(btnAccSet);
		panel5.add(btnAccCheck);
		
		//End panel 5
		
		content.add(panel0);
		
		btnCreate = new JButton("Create R");
		btnCreate.setBounds(10, 51, 80, 20);
		panel0.add(btnCreate);
		btnCreate.setFont(new Font("Arial", Font.PLAIN, 11));
		btnCreate.setName("CREATE");
		
		btnCreateUtil = new JButton("Create U");
		btnCreateUtil.setBounds(105, 51, 80, 20);
		panel0.add(btnCreateUtil);
		btnCreateUtil.setFont(new Font("Arial", Font.PLAIN, 11));
		btnCreateUtil.setName("CREATE_UT");
		
		btnCreateAcc = new JButton("Create A");
		btnCreateAcc.setBounds(200, 51, 80, 20);
		panel0.add(btnCreateAcc);
		btnCreateAcc.setFont(new Font("Arial", Font.PLAIN, 11));
		btnCreateAcc.setName("CREATE_ACC");
		btnCreateAcc.addActionListener(this);
		btnCreateUtil.addActionListener(this);
		btnCreate.addActionListener(this);
		content.add(panel1);
		
		btnLoadXml = new JButton("Load");
		btnLoadXml.setBounds(200, 41, 79, 20);
		panel1.add(btnLoadXml);
		btnLoadXml.setFont(new Font("Arial", Font.PLAIN, 11));
		btnLoadXml.setName("LOAD");
		
		btnLoadXml.addActionListener(this);
		content.add(panel2);
		content.add(panel3);
		content.add(panel4);
		
		lblEnumItemaValues = new JLabel("ENUM Items values");
		lblEnumItemaValues.setBounds(10, 102, 150, 14);
		panel4.add(lblEnumItemaValues);
		content.add(panel5);
		
		JLabel lblCondition = new JLabel("Condition");
		lblCondition.setBounds(10, 53, 80, 14);
		panel5.add(lblCondition);
		btnFeature.addActionListener(this);
		btnSet.addActionListener(this);
		btnDateNow.addActionListener(this);
		btnPrint.addActionListener(this);
		btnSend.addActionListener(this);
		jmi1.addActionListener(this);
		btnUtilCalc.addActionListener(this);
		btnUtilSet.addActionListener(this);
		btnAccSet.addActionListener(this);
		btnAccCheck.addActionListener(this);
		
		listFeatures.addMouseListener(new MouseAdapter() {
		     public void mouseClicked(MouseEvent me) {
		       // if right mouse button clicked (or me.isPopupTrigger())
		       if (SwingUtilities.isRightMouseButton(me)
		           && !listFeatures.isSelectionEmpty()
		           && listFeatures.locationToIndex(me.getPoint())
		              == listFeatures.getSelectedIndex()) {
		               popupMenu.show(listFeatures, me.getX(), me.getY());
		               }
		           }
		        }
		     );
		
		cmbResources.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) 
			{
				if(adding)return;
				
				int index = cmbResources.getSelectedIndex();
				String key = (String)cmbResources.getItemAt(index);
				//System.out.println("key: " + key);
				LoadResource(resourcesStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});
		
		
		cmbUtilityFc.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) 
			{
				int index = cmbUtilityFc.getSelectedIndex();
				String key = (String)cmbUtilityFc.getItemAt(index);
				LoadUtilityFunction(utilityFunctionStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});
		
		
		cmbAccFc.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				int index = cmbAccFc.getSelectedIndex();
				String key = (String)cmbAccFc.getItemAt(index);
				
				LoadValuesRangeFunction(valuesRangeStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});
		
		
		//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		addWindowListener(new	WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				myAgent.doDelete();
			}
		} );
	}//ResourceAgentGui(ResourceAgent a)

	@Override
	/**
	 * Obsluga zadarzen - nacisniecia przyciskow
	 */
	public void actionPerformed(ActionEvent e) 
	{
		JComponent source = (JComponent)e.getSource();
		
		/*
		 * Przycisk [Add]
		 * Dodaje nazwe cechy i typ do obiektu HashMap<String, FeatureType> features
		 */
		if(source.getName().compareTo("FEATURE") == 0)
		{
			/*
			 * Dodoanie nazwy i typu cechy. Jezeli cecha o danej nazwie istnieje zostanie zastapiona
			 */
			if(txtFeatureName.getText().compareTo("") != 0)
			{
				features.put(txtFeatureName.getText(), (FeatureType)cmbTypes.getSelectedItem());
				//listModel.addElement(txtFeatureName.getText() + " : " + features.get(txtFeatureName.getText()));
			}
			
			/*
			 * Odswierzenie nazw i typow cech w oknie JList w oparciu o obiekt features
			 */
			listModel.clear();
			Iterator it = features.keySet().iterator();
			while (it.hasNext()) 
			{
				String key = (String)it.next();
				listModel.addElement(key + " : " + features.get(key));
				//listModel.addElement(key + " : " + features.get(key));
			}
			
			/*
			 * Dodawanie lub zmiana powoduje usuniecie obiektow Resource, jezeli np. zostaly wczesniej utworzone
			 */
			resourceType = null;
			resource = null;
			
			return;
		}
		
		/*
		 * Przycisk [Create R]
		 * Tworzy nowy egzemplarz zasobu na podstawie zdefiniowanych cech
		 */
		if(source.getName().compareTo("CREATE") == 0)
		{
			ResourceTypeBuilder rtb = new ResourceTypeBuilder("");
			ResourceType resourceTypeTmp;
			
			resourceTypeTmp = rtb.GetResourceType((String)cmbTypesXml.getSelectedItem());
			Resource resourceTmp = new Resource(resourceTypeTmp);
			AddResource(resourceTmp);
			resource = resourceTmp;
			return;
		}//CREATE
		
		/**
		 * Ustawienie wartosci dla stworzonego obiektu iResource resource
		 */
		if(source.getName().compareTo("SET") == 0)
		{
			if(resource != null)
			{
				resource.setOwner(txtOwner.getText());
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
				df.setTimeZone(TimeZone.getTimeZone("UTC"));
				try {
					Date dt = df.parse(txtValidDate.getText());
					resource.setValidDate(dt);
				} catch (ParseException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
				
				for(int i = 0; i<model.getRowCount(); i++)
				{
					try 
					{
						String fKey = (String)model.getValueAt(i, 0);
						FeatureType fType = (FeatureType)model.getValueAt(i, 1);
						switch(fType)
						{
						case INT:
							Integer fValuei = Integer.parseInt((String)model.getValueAt(i, 2));
							resource.setFeatureValue(fKey, fValuei);
							break;
						case FLOAT:
							Float fValuef = Float.parseFloat((String)model.getValueAt(i, 2));
							resource.setFeatureValue(fKey, fValuef);
							break;
						case ENUM:
							String fValuee = (String)model.getValueAt(i, 2);							
							resource.setFeatureValue(fKey, fValuee);
							break;
						}
						
						//resource.SetFeatureValue((String)model.getValueAt(i, 0), model.getValueAt(i, 2));
					} 
					catch (InvalidFeatureNameException e1) 
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
					catch (InvalidFeatureTypeException e1) 
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (InvalidFeatureValueException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			
			
			
			return;
		}
		
		if(source.getName().compareTo("NOW") == 0)
		{
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
			df.setTimeZone(TimeZone.getTimeZone("UTC"));
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MINUTE, 5);
			Date dt = calendar.getTime();
			String dts = df.format(dt);
			txtValidDate.setText(dts);
			
			return;
		}
		
		/**
		 * Wyswietla informacje na temat utworzonego zasobu
		 */
		if(source.getName().compareTo("PRINT") == 0)
		{
			if(resource == null)
			{
				System.out.println("ERROR: No resource. Create and set resource !");
				return;
			}
			resource.printResourceInfo();
			/*
			System.out.println("Resource Type name : " + resource.GetType().GetStoreTypeName());
			System.out.println("Resource Owner     : " + resource.GetOwner());
			
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
			df.setTimeZone(TimeZone.getTimeZone("UTC"));
			String dts = df.format(resource.GetValidDate());
			System.out.println("Resource Valid Date: " + dts);
			
			System.out.println("Features-->");
			
			Iterator it = resource.GetType().GetFeaturesCollection().keySet().iterator();
			while(it.hasNext())
			{
				String key = (String)it.next();
				try {
					System.out.println("Name: " + key  + ",  Type: " + resource.GetFeatureType(key) + ",  Value: " + resource.GetFeatureValue(key));
				} catch (InvalidFeatureNameException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
			}
			*/
			
			
			return;
		}
		
		/**
		 * Wyslanie zasobu do innego agenta
		 */
		if(source.getName().compareTo("SEND") == 0)
		{
			if(this.resource != null)
			{
				myAgent.SendResource(resource, txtSend.getText());
			}
			
			return;
		}
		
		/**
		 * Usuniecie zaznaczonej cechy
		 */
		if(source.getName().compareTo("DELETE") == 0)
		{
			String key = (String)listModel.elementAt(listFeatures.getSelectedIndex());
			int index = 0;
			for(int i = 0; i<key.length(); i++)
			{
				if(key.charAt(i) == ' ')
				{
					index = i;
					break;
				}
			}
			key = key.substring(0, index);
			features.remove(key);
			
			listModel.clear();
			Iterator it = features.keySet().iterator();
			while (it.hasNext()) 
			{
				String key2 = (String)it.next();
				listModel.addElement(key2 + " : " + features.get(key2));
			}
			
			return;
		}
		
		if(source.getName().compareTo("LOAD") == 0)
		{
			/*
			features.clear();
			ResourceType tmpType = typeBuilder.GetResourceType((String)cmbTypesXml.getSelectedItem());
			//tmpType.
			
			txtResourceName.setText(tmpType.GetResourceTypeName());
			
			features = tmpType.GetFeaturesCollection();
			
			listModel.clear();
			Iterator it = features.keySet().iterator();
			while (it.hasNext()) 
			{
				String key = (String)it.next();
				listModel.addElement(key + " : " + features.get(key));
				//listModel.addElement(key + " : " + features.get(key));
			}
			*/
			//resourceType = new iResourceType(txtResourceName.getText(), features);
			//resource = new iResource(resourceType);
			/*
			HashMap<String, FeatureType> featuresTmp = new HashMap<String, FeatureType>();
			Iterator<String> it = features.keySet().iterator();
			while(it.hasNext())
			{
				String key = it.next();
				FeatureType type = features.get(key); 
				featuresTmp.put(key, type);
			}
			ResourceType resourceTypeTmp = new ResourceType(txtResourceName.getText(), featuresTmp);
			Resource resourceTmp = new Resource(resourceTypeTmp);
						
			AddResource(resourceTmp);
			//LoadResource(resource);
			return;
			*/
			return;
		}
		
		/*
		 * Zapisanie nowych wartosci do aktywnego obiektu utilityFunction
		 */
		if(source.getName().compareTo("UT_SET") == 0)
		{
			utilityFunction.setExpression(txtUtilityStr.getText());
			//modelUtilities.
			
			for(int i = 0; i<modelUtilities.getRowCount(); i++)
			{
				String fType = (String)modelUtilities.getValueAt(i, 0);
				String en = (String)modelUtilities.getValueAt(i, 1);
				Integer iValue = Integer.parseInt((String) modelUtilities.getValueAt(i, 2));
				
				try {
					utilityFunction.setEnumValue(fType, en, iValue);
				} catch (InvalidFeatureNameException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (InvalidEnumTypeException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			return;
		}
		
		if(source.getName().compareTo("UT_CALC") == 0)
		{
			try 
			{
				float utlt = utilityFunction.calculateUtility(resource);
				JOptionPane.showMessageDialog((Component) e.getSource(), "Utility: " + utlt, "Calculated utility for active resource", JOptionPane.INFORMATION_MESSAGE);
			}
			catch (InvalidResourceTypeException e1) 
			{
				JOptionPane.showMessageDialog((Component) e.getSource(), e1.getMessage(), "InvalidResourceTypeException", JOptionPane.ERROR_MESSAGE);
				//e1.printStackTrace();
			}
			return;
		}
		
		if(source.getName().compareTo("CREATE_UT") == 0)
		{
			//UtilityFunction utf = new
			ResourceType tmpType;
			
			tmpType = typeBuilder.GetResourceType((String)cmbTypesXml.getSelectedItem());
			ResourceUtility utf = new ResourceUtility(tmpType);				
			AddUtilityFunction(utf);
			return;
		}
		
		if(source.getName().compareTo("CREATE_ACC") == 0)
		{
			ResourceType tmpType;
			
			tmpType = typeBuilder.GetResourceType((String)cmbTypesXml.getSelectedItem());
			ResourceValidation rvr = new ResourceValidation(tmpType);				
			AddValuesRangeFunction(rvr);
			return;
		}
		
		if(source.getName().compareTo("ACC_SET") == 0)
		{
			valuesRange.setCondition(this.txtValuesStr.getText());
			/*
			for(int i = 0; i<modelAcc.getRowCount(); i++)
			{
				String key = (String)modelAcc.getValueAt(i, 0);
				String expr = (String)modelAcc.getValueAt(i, 1);
				
				try {
					valuesRange.SetCondition(key, expr);
				} catch (InvalidFeatureNameException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			*/
			//valuesRange.SetCondition(name, condition)
			return;
		}
		
		if(source.getName().compareTo("ACC_CHECK") == 0)
		{
			boolean result = true;
			StringBuilder sb = new StringBuilder();
			//HashMap<String, Boolean> results;
			try {
				result = valuesRange.validateCondition(resource);
				//Iterator<String> it = results.keySet().iterator();
				//while(it.hasNext())
				//{
				//	String key = it.next();
					//if(results.get(key) == false)
					//{
					//	result = false;
					//	sb.append("Feature: " + key + " -> NOT ACCEPTABLE\n");
					//}
					//else
					//{
					//	sb.append("Feature: " + key + " -> ACCEPTABLE\n");
					//}
						
						
				//}
				
				
			} catch (ParseExpressionErrorException e2) {
				// TODO Auto-generated catch block
				//e2.printStackTrace();
				JOptionPane.showMessageDialog((Component) e.getSource(), e2.getStackTrace(), "InvalidResourceTypeException", JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			/*
			try {
				result = valuesRange.IsResourceAcceptable(resource);
			} catch (InvalidResourceTypeException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				JOptionPane.showMessageDialog((Component) e.getSource(), e1.getStackTrace(), "InvalidResourceTypeException", JOptionPane.ERROR_MESSAGE);
			} catch (InvalidFeatureNameException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				JOptionPane.showMessageDialog((Component) e.getSource(), e1.getStackTrace(), "InvalidFeatureNameException", JOptionPane.ERROR_MESSAGE);
			}
			*/
			
			if(result)
			{
				JOptionPane.showMessageDialog((Component) e.getSource(), "Resource: ACCAPTABLE\n\n" + sb.toString(), "Validation result:", JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
				JOptionPane.showMessageDialog((Component) e.getSource(), "Resource: NOT ACCAPTABLE\n\n" + sb.toString(), "Validation result:", JOptionPane.ERROR_MESSAGE);
			}
			return;
		}
	}//actionPerformed(ActionEvent e)
	
	public String DateToFormatedString(Date dt)
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		String dts = df.format(dt);
		return dts;
	}
	
	public Date FormatedStringToDate(String dts) throws ParseException
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		Date dt = df.parse(dts);
		return dt;
	}
	
	public void AddUtilityFunction(ResourceUtility utl)
	{
		int items = utilityFunctionStore.size();
		String name = utl.getResourceTypeName();
		name = name + " [" + items + "]";
		utilityFunctionStore.put(name, utl);
		cmbUtilityFc.addItem(name);
		cmbUtilityFc.setSelectedItem(name);
		
		LoadUtilityFunction(utl);
	}
	
	public void AddValuesRangeFunction(ResourceValidation rvr)
	{
		int items = valuesRangeStore.size();
		String name = rvr.getType().getResourceTypeName();
		name = name + " [" + items + "]";
		valuesRangeStore.put(name, rvr);
		cmbAccFc.addItem(name);
		cmbAccFc.setSelectedItem(name);
		
		LoadValuesRangeFunction(rvr);
	}
	
	/**
	 * Dodaje nowy zasob do kolekcji zasobow
	 * @param res
	 */
	public void AddResource(Resource res)
	{
		adding = true;
		int items = resourcesStore.size();
		String name = res.getType().getResourceTypeName() + " [" + items + "]";
		resourcesStore.put(name, res);
		cmbResources.addItem(name);
		cmbResources.setSelectedItem(name);
		
		LoadResource(resourcesStore.get(name));
		
		adding = false;
		//cmbResources.removeAllItems();
		
		//Iterator<String> it = resourcesStore.keySet().iterator();
		//while(it.hasNext())
		//{
		//	String key = it.next();
		//	cmbResources.addItem(key);
		//}		
	}
	
	/**
	 * Laduje szczegoly zasobu do okna edycyjnego i ustawia zaladowany zasob jako aktywny
	 * @param res
	 */
	public void LoadResource(Resource res)
	{
		int rowsCount = 0;
		ResourceType resType = res.getType();
		
		txtUUID.setText(res.getUUID());
		
		/**
		 * Wyczyszczenie tabeli
		 */
		for( int i = model.getRowCount() - 1; i >= 0; i-- )
		{
		    model.removeRow(i);
		}
		
		/**
		 * Utworzenie tabeli JTable dt pozwalajecej wrowadzic wartosci cech utworzonego zasobu
		 */
		Iterator it = res.getType().getFeaturesCollection().keySet().iterator();
		while (it.hasNext()) 
		{
			String key = (String)it.next();
			System.out.println("f: " + key);
			//rowsCount = dt.getRowCount();
			try
			{
				FeatureType type = res.getFeatureType(key);
				Object ob = res.getFeatureValue(key);
				if(ob==null)
				{
					model.insertRow(rowsCount, new Object[]{key,  res.getFeatureType(key), null});
				}
				else
				{
					switch(type)
					{
					case INT:
						model.insertRow(rowsCount, new Object[]{key,  res.getFeatureType(key), ((Integer)ob).toString()});						
						break;
					case FLOAT:
						model.insertRow(rowsCount, new Object[]{key,  res.getFeatureType(key), ((Float)ob).toString()});
						break;
					default:
						model.insertRow(rowsCount, new Object[]{key,  res.getFeatureType(key), ob});
						break;
					}
				}
				
				rowsCount++;
			}
			catch (InvalidFeatureNameException ex) 
			{
				ex.printStackTrace();
			} 
		}
		
		/**
		 * DLA TYPOW ENUM
		 * Modyfikacja komorek tabeli (danego wiersza) aby mozna bylo wyswietlic obiekt JComboBox
		 */
		EachRowEditor rowEditor = new EachRowEditor(dt);
		for(int i = 0; i<dt.getRowCount(); i++)
		{
			if(dt.getValueAt(i, 1) == FeatureType.ENUM)
			{
				/**
				 * Utworzenie obiektu JComboBox wartosci enum przylkadowego typu
				 * Obiekt ten zostanie umieszczony w tabeli
				 */
				JComboBox cmbTypesV = new JComboBox();
				//try 
				//{
					//Class cl = Class.forName(typeBuilder.GetEnumTypeName(resType.GetResourceTypeName(), (String)dt.getValueAt(i, 0)));
					//Enum[] ev = (Enum[])cl.getEnumConstants();
					
					String[] ev = resType.getEnumTypes().get((String)dt.getValueAt(i, 0)).getArray();
					
					for(String v: ev)
					{
						cmbTypesV.addItem(v);
					}
				//} catch (ClassNotFoundException e1) {
				//	e1.printStackTrace();
				//}
				
				
				//for(EnumValues v: EnumValues.values())
				//{
				//	cmbTypesV.addItem(v);
				//}
				
				rowEditor.setEditorAt(i, new DefaultCellEditor(cmbTypesV));
			}
		}
		dt.getColumn("Feature Value").setCellEditor(rowEditor);
		
		txtOwner.setText(res.getOwner());
		Date dt = res.getValidDate();
		if(dt!=null)
		{
		    txtValidDate.setText(DateToFormatedString(dt));
		}
		else
		{
			txtValidDate.setText("yyyy-MM-ddTHH:mm:ss.SSS");
		}
		
		resource = res;
		resourceType = res.getType();
	}
	
	public void LoadUtilityFunction(ResourceUtility utl)
	{
		this.utilityFunction = utl;
		int rowsCount = 0;
		
		txtUtilityStr.setText(utilityFunction.getExrpession());

		/**
		 * Wyczyszczenie tabeli
		 */
		for( int i = modelUtilities.getRowCount() - 1; i >= 0; i-- )
		{
			modelUtilities.removeRow(i);
		}
		
		Iterator<String> it1 = utilityFunction.getTableNames().iterator();
		while(it1.hasNext())
		{
			String key = it1.next();
			
			Iterator<String> it2 = utilityFunction.getTableValues(key).keySet().iterator();
			
			while(it2.hasNext())
			{
				String en = it2.next();
				Integer v = utilityFunction.getTableValues(key).get(en);
				
				modelUtilities.insertRow(rowsCount, new Object[]{key, en, v.toString()});
				rowsCount++;
			}
			
		}
	}
	
	public void LoadValuesRangeFunction(ResourceValidation rvr)
	{
		this.valuesRange = rvr;
		int rowsCount = 0;
		this.txtValuesStr.setText(rvr.getCondition());
		
		/*
		for( int i = modelAcc.getRowCount() - 1; i >= 0; i-- )
		{
			modelAcc.removeRow(i);
		}
		
		Set<String> fNames = rvr.GetFeaturesNames();
		Iterator<String> it  = fNames.iterator();
		while(it.hasNext())
		{
			String key = it.next();
			try {
				modelAcc.insertRow(rowsCount, new Object[]{key, rvr.GetCondition(key)});
			} catch (InvalidFeatureNameException e) {
				e.printStackTrace();
			}
		}
		*/
		
	}
	
	public void LoadFromXml(String fileName)
	{
		typeBuilder = new ResourceTypeBuilder(fileName);
		List<String> types = typeBuilder.GetResourceTypeNames();
		
		Iterator it = types.iterator();
		
		while(it.hasNext())
		{
			String type = (String)it.next();
			cmbTypesXml.addItem(type);
		}
	}
	
	public void showGui()
	{
		super.setVisible(true);
	}
}
